package com.imooc.web.config;

import com.imooc.filter.TimeFilter;
import com.imooc.intercerptor.TimeInterceptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.AsyncSupportConfigurer;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by zghgchao 2018/4/15 15:37
 * 这里配置的FilterRegistrationBean和TimeFilter中的 @Component效果一样
 */
//@Configuration//告诉spring这是一个配置类
public class WebConfig extends WebMvcConfigurerAdapter{

//    @Autowired//将声明成组件的类（已经过spring初始化）拿来
    private TimeInterceptor timeInterceptor;

    /**
     * 使拦截器生效
     * @param registry
     */
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
//        registry.addInterceptor(timeInterceptor);//将自定义拦截器注册到interceptors中
    }

    /**
     * 配置SpringMVC对异步的支持
     * @param configurer
     */
    @Override
    public void configureAsyncSupport(AsyncSupportConfigurer configurer) {
        super.configureAsyncSupport(configurer);
    }

    //    @Bean
    public FilterRegistrationBean timeFilter(){
        FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean();

        TimeFilter timeFilter = new TimeFilter();
        filterRegistrationBean.setFilter(timeFilter);//将自定义TimeFilter注册到过滤器Bean上

        List<String> urls = new ArrayList<>();
        urls.add("/*");
        filterRegistrationBean.setUrlPatterns(urls);//配置过滤器的URL拦截地址

        return filterRegistrationBean;
    }
}
